package org.feng.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;

import lombok.AllArgsConstructor;
import org.feng.entity.Dept;
import org.feng.base.entity.Result;
import org.feng.service.DeptService;
import org.feng.utils.ExcelReadListener;
import org.feng.utils.ExcelUtils;
import org.feng.utils.TreeUtil;
import org.feng.utils.condition.Condition;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author feng
 * @since 2021-08-27
 */
@RestController
@RequestMapping("/system/dept")
@AllArgsConstructor
public class DeptController {

    private final DeptService deptService;

    @PostMapping("/imports")
    public void imports(MultipartFile file) throws IOException {
        ArrayList<Dept> list = new ArrayList<>();
        EasyExcel.read(file.getInputStream(), Dept.class, new ExcelReadListener<Dept>(list)).sheet().doRead();
        System.out.println("接收完成");
    }

    /**
     * 导出
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        ExcelUtils.writeExcel(response, deptService.list(), Dept.class);
    }

    /**
     * 列表
     */
    @GetMapping
    public Result<List<Dept>> list(Dept dept) {
        return Result.success(TreeUtil.tree(deptService.list(Condition.getQueryWrapper(dept))));
    }

    /**
     * 分页列表
     */
    @GetMapping("/page")
    public Result<IPage<Dept>> page(Dept dept) {
        return Result.success(deptService.page(Condition.getPage(), Condition.getQueryWrapper(dept)));
    }

    /**
     * 详情
     */
    @GetMapping("/query")
    public Result<Dept> detail(@RequestParam Long id) {
        return Result.success(deptService.getById(id));
    }

    /**
     * 新增
     */
    @PostMapping
    public Result<Boolean> save(@RequestBody Dept dept) {
        return Result.status(deptService.save(dept));
    }

    /**
     * 修改
     */
    @PutMapping
    public Result<Boolean> update(@RequestBody Dept dept) {
        return Result.status(deptService.updateById(dept));
    }

    /**
     * 删除
     */
    @DeleteMapping
    public Result<Boolean> delete(@RequestParam String ids) {
        return Result.status(deptService.removeByIds(Arrays.asList(ids.split(","))));
    }
}

